<?php

	require "config.php";

	function logme($string)
	{
		if (!Config::logging) return;
		if (is_array($string))
		{
			echo "<span style=\"color: gray\"><b>Log:</b><pre>";
			print_r($string);
			echo "</pre></span><br>\n";
		}
		else
			echo "<span style=\"color: gray\"><b>Log:</b> {$string}</span><br>\n";
	}
	
	function error($string)
	{
		die("<span style=\"color: red\"><b>Error:</b> ". $string . "</span><br>\n");		
		//echo "<script type=\"text/javascript\">alert('Error: {$string}')</script>";
	}

	
	class Dispatcher
	{
	
		function try_to_call($controller_name, $method_name)
		{
			$forbidden_methods = array("render_view");
			if (in_array($method_name, $forbidden_methods))
				error("Method {$method_name} does not exists");
			
			try
			{
				$controller_reflection = new ReflectionClass($controller_name);
				$method_reflection = $controller_reflection->getMethod($method_name);
				if ($method_reflection && $method_reflection->isPublic())
				{
					$controller_instance = $controller_reflection->newInstance();
					// call method
					$method_reflection->invoke($controller_instance);
					// render view (render_view itself checks if view exists)
					$controller_instance->render_view($method_name);

				}
				else 
					error($method_name . " is not public.");
			}
			catch (ReflectionException $e)
			{
				error($e->getMessage());
			}
			
		}


		function include_user_files()
		{
			$dirs = array("models", "controllers");
	
			foreach ($dirs as $start_dir)
			{
				$dir = dirname(__FILE__) . "/{$start_dir}/";
				if (!file_exists($dir)) error("No {$start_dir} directory found.");
			
				$handler = opendir($dir);
			    while ($file = readdir($handler)) 
				{
			        if ($file != '.' && $file != '..' && substr($file, -4, 4) == ".php")
					{	
						logme("Including file {$dir}{$file}");
						include_once($dir . $file);
					}
			    }
			    closedir($handler);
			}
		}


		function dispatch()
		{
			$request_uri = explode('/', substr($_SERVER['REQUEST_URI'], strlen(Config::root_path))); 

			// /api/authors/add ---> [0] = , [1] = api [2] = authors [3] = add
			if ($request_uri[1] == "api")
			{
				$controller_name = $request_uri[2] ? ucfirst($request_uri[2]) . "Controller" : "IndexController";
				$method_name = $request_uri[3] ? $request_uri[3] : "index";
				
				$this->try_to_call($controller_name, $method_name);
			}
			else
				echo "No controller/method";
		}
	}
	
	require "framework/controller.php";
	require "framework/model.php";
	
	$dispatcher = new Dispatcher();
	$dispatcher->include_user_files();
	$dispatcher->dispatch();
?>